var Story = function(params) { this.data = params; };
var clickable = true;
var publishing = false;

$(document).ready(function() {

	if ($('#story_youtube').val()!='http://youtu.be/') {
		$('#youtube_span').show();
	}

	if ($('#story_photos').val()!='') {
		$('#photos_span').show();
	}

	if ($('#story_source').val()!='http://') {
		$('#external_span').show();
	}

	$('#story_youtube').live('keyup focus blur', function() {
		if ($('#story_youtube').val()!='') {
			$('#youtube_span').show();
		}else {
			$('#youtube_span').hide();
		}
	});

	$('#story_photos').live('keyup focus blur', function() {
		if ($('#story_photos').val()!='') {
			$('#photos_span').show();
		}else {
			$('#photos_span').hide();
		}
	});

	$('#story_source').live('keyup focus blur', function() {
		if ($('#story_source').val()!='') {
			$('#external_span').show();
		}else {
			$('#external_span').hide();
		}
	});

	$('#youtube_span').click(function() {
		$('#story_youtube').val('').focus();
		$('#youtube_span').hide();
	});

	$('#photos_span').click(function() {
		$('#story_photos').val('').focus();
		$('#photos_span').hide();
	});

	$('#external_span').click(function() {
		$('#story_source').val('').focus();
		$('#external_span').hide();
	});
});

Story.prototype.save = function(storyData, button) {
	this.setState('loading');
	var REQ_PATH = API2_PATH;
	switch(storyData.req_type) {
		case 'new':
			REQ_PATH += 'newstory';
			break;
		case 'edit':
			REQ_PATH += 'editstory';
			break;
		case 'del':
			REQ_PATH += 'deletestory';
			break;
		case 'upload':
			REQ_PATH += 'uploadstory';
			break;
	}

	if (button) { $(button).addClass(this.data['spinner_class']); }
	$.post(REQ_PATH, storyData,
			(function(st) {
				return function(data) {
					if (data) {
						if (!data.hasOwnProperty('error_count') || data['error_count'] > 0) {
							st.setState('errors', data);
							publishing = false;
						}
						else {
							if (storyData.req_type == 'new') {
								st.newStorySuccess(data);
							}
							else if (storyData.req_type == 'edit') {
								st.editStorySuccess(data);
							}
							else if (storyData.req_type == 'del') {
								st.deleteStorySuccess(data);
							}
						}
					}
					$("." + st.data['spinner_class']).removeClass(st.data['spinner_class']);
					clickable = true;
				};
			})(this)
			);
}

Story.prototype.newStorySuccess = function(storyData) {
	this.setState('saved');
	if (storyData['publish']) {
		var url = this.data['site_root'] + '/' + storyData['story_url'] + '?d=' + storyData['upload_msg'];
		location.href = url;
	}
	else {
		$('#story_id').val(storyData['id']);
		$('#story_groupid option:first').prop({ value: storyData['groupid'], selected: 'selected' });
		$('#save_new_button').hide();
		$('#terms_row').hide();
		$('#save_existing_button').show();
		$('#form_header_text').html('Edit Story');
		this.handleContentReview(storyData);
	}
}

Story.prototype.editStorySuccess = function(storyData) {
	this.setState('saved');
	if (storyData['publish']) {
		var url = this.data['site_root'] + '/' + storyData['story_url'] + '?d=' + storyData['upload_msg'];
		location.href = url;
	}
	else {
		this.handleContentReview(storyData);
	}
}

Story.prototype.handleContentReview = function(data) {
	if(data['upload_msg'] == 'r') {
		$.facebox({ajax:'dialog/restricted?id='+$('#story_id').val()+'&title='+$('#story_title').val()});
		$('#flag_private').click(); // show the user it's now private
		$('#basic_options').hide();
		$('#advanced_options').show();
		$('#toggle_basic_text').hide();
		$('#toggle_basic_link').show();
		$('#toggle_advanced_link').hide();
		$('#toggle_advanced_text').show();
	}
	else if (data['upload_msg'] == 'm') {
		$.facebox({ajax:'dialog/mature?id='+$('#story_id').val()+'&title='+$('#story_title').val()});
		$('#story_rating').val(4) // show the user its now rated R
	}
}

Story.prototype.deleteStorySuccess = function(storyData) {
	$('#my_stories').html(storyData['my_stories']);
}

Story.prototype.getStoryData = function() {
	var fields = ['id', 'title', 'language', 'tags', 'source', 'copyright',
		'flag1', 'youtube', 'photos', 'groupid', 'rating',
		'category1', 'category2', 'draft', 'authorid', 'distributable'];

	var sdata = {};
	for (var i = 0; i < fields.length; i++) {
		var fname = 'story_' + fields[i];
		if (fname == 'story_flag1') {
			sdata[fields[i]] = $("input:radio[name='" + fname + "']:checked").val();
		}else if (fname == 'story_photos'){
			sdata[fields[i]] = $('#' + fname).val().replace(/\?action=view&current=/, '');
		}else if (fname == 'story_title' && $('#story_title').is('.story_title_default')){
			sdata[fields[i]] = '';
		}else {
			sdata[fields[i]] = $('#' + fname).val();
		}
	}
	// we came in on an 'Add Part' to an existing groupless story
	// store the groupless story's id so we can add them both
	// to the new group we'll create for the current story
	if (this.data['add_to_new'] != false) {
		sdata['add_to_new'] = this.data['add_to_new'];
	}
	return sdata;
};

Story.prototype.clearErrors = function() {
	$('#error_state').hide();
	$('#error_list').html('');
}

Story.prototype.showErrors = function(data) {
	$('#story_state').hide();
	$('#publish_state').hide();
	if (data['error']) {
		$('#error_list').append('<li>' + data['error'] + '</li>');
	}
	if (data['errors']) {
		$.each(data['errors'], function(error_field, error_message){
			$('#error_list').append('<li>- ' + error_message + '</li>');
		});
	}
	$('#error_state').show();
}

Story.prototype.disableButtons = function() {
	$("#save_new_button").unbind('click', saveNewStory);
	$("#save_existing_button").unbind('click', saveExistingStory);
	$("#publish_button").unbind('click', publishStory);
}

Story.prototype.enableButtons = function() {
	$("#save_new_button").bind('click', saveNewStory);
	$("#save_existing_button").bind('click', saveExistingStory);
	$("#publish_button").bind('click', publishStory);
	$("#publish_button").attr('disabled','');
	clickable = true;
}

Story.prototype.setState = function(state, data) {
	switch(state) {
		case 'loading':
			this.clearErrors();
			$('#story_state').show();
			$('#publish_state').show();
			$('#save_state').removeClass('state_green');
			$('#save_state').removeClass('state_red');
			$('#save_state').addClass('state_black');
			$('#save_state').html('Saving...');
			break;
		case 'errors':
			this.clearErrors();
			this.showErrors(data);
			this.enableButtons();
			break;
		case 'saved':
			this.clearErrors();
			this.data['dirty'] = false;
			$('#story_state').show();
			$('#save_state').removeClass('state_black');
			$('#save_state').removeClass('state_red');
			$('#save_state').addClass('state_green');
			$('#save_state').html('Saved');
			if(this.data['autosave']) {
				this.data['autoSaveID'] = setInterval("autoSaveStory();", 7000);
			}
			break;
		case 'unsaved':
			this.data['dirty'] = true;
			if ($('#save_state').is(':visible')) {
				$('#save_state').html('Unsaved');
				$('#save_state').removeClass('state_green');
				$('#save_state').addClass('state_red');
			}
			break;
		default:
			break;
	}
}

Story.prototype.init = function() {
	this.data['dirty'] = false;
	//this.data['autosave'] = true;

	if ($('#step_2').is(':visible')) {
		if ($('#upload_story_button').length) {
			this.uploader = new qq.FileUploader({
				element: $('#upload_story_button')[0],
				action: '/apiv2/uploadstory',
				allowedExtensions: ['txt'],
				sizeLimit: 0,
				params : {
					// IE needs text/html even when it wants json
					output: ($.browser.msie) ? 'json_html' : 'json',
					language: $('#story_language').val(),
					authorid: $('#story_authorid').val()
				},
				onSubmit: function(id, fileName){ $('.qq-upload-list').html(''); },
				onComplete: function(id, fileName, responseJSON){
					if (typeof(tinyMCE) !== 'undefined') { // will be undefined if tinyMCE fails to load
						var editor = tinyMCE.get('story_text');
						editor.setContent(responseJSON['processed_text']);
					}
					else {
						// remove tags and HTML entities for textarea
						$('#story_text').val(responseJSON['processed_text'].replace(/<br[^>\n\w]*>/gi,"\n").replace(/<p[^>\n\w]*>/gi,"").replace(/<\/p[^>\n\w]*>/gi,"\n\n").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,String.fromCharCode(34)));
					}
				}
			});
		}

		$('#step_2 img[title]').tipsy({ gravity:'sw', html:true, fade:true, delayOut:1000});
	}

	this.data['spinner_class'] = 'button_spinner';

	if ($('#story_id').val() === 'new') {
		$('#save_new_button').show();
	}
	else {
		if(this.data['autosave']) {
			this.data['autoSaveID'] = setInterval("autoSaveStory();", 3000);
		}
		$('#save_existing_button').show();
	}

	$('.toggle_options').live('click', {st:this}, function() {
		if ($('#toggle_advanced_link').is(":visible")) {
			$('#basic_options').hide();
			$('#advanced_options').show();
			$('#toggle_basic_text').hide();
			$('#toggle_basic_link').show();
			$('#toggle_advanced_link').hide();
			$('#toggle_advanced_text').show();
		}
		else {
			$('#advanced_options').hide();
			$('#basic_options').show();
			$('#toggle_basic_text').show();
			$('#toggle_basic_link').hide();
			$('#toggle_advanced_link').show();
			$('#toggle_advanced_text').hide();
		}
		return false;
	});

	$('.edit_group').live('click', {st:this}, function() {
		if (!isMobile()){
			$.facebox({ajax:'dialog/editgroup?groupid='+$(this).attr('id').split('_')[1]});
			return false;
		}
		else {
			location.href = "dialog/editgroup?groupid="+$(this).attr('id').split('_')[1];
		}
	});

	$('.delete_group').live('click', {st:this}, function() {
		$(this).find('img').last().hide();
		$(this).find('img').first().show();

		if (confirm("Are you sure you want to permanently delete this entire story?\n\nAll chapters in the story will also be deleted!") === true) {
			var storyGroup = new StoryGroup({});
			var groupData = {};
			var groupAttrs = $(this).attr('id').split('_');
			groupData['req_type'] = 'del';
			groupData['id'] = groupAttrs[1];
			groupData['ownerid'] = groupAttrs[3];
			$(this).unbind('click');
			storyGroup.save(groupData, false);
		}
		else {
			$(this).find('img').first().hide();
			$(this).find('img').last().show();
		}
		return false;
	});

	$('.delete_story, .delete_solo_story').live('click', {st:this}, function() {
		$(this).find('img').last().hide();
		$(this).find('img').first().show();

		var noun = /solo/.test($(this).attr('class')) ? 'story' : 'chapter';

		if (confirm("Are you sure you want to permanently delete this "+noun+"?") === true) {
			var story = new Story({});
			var storyData = {};
			var storyAttrs = $(this).attr('id').split('_');
			storyData['req_type'] = 'del';
			storyData['id'] = storyAttrs[1];
			storyData['authorid'] = storyAttrs[3];
			$(this).unbind('click');
			story.save(storyData, false);
		}
		else {
			$(this).find('img').first().hide();
			$(this).find('img').last().show();
		}
		return false;
	});

	$('#save_new_button').bind('click', {st:this}, saveNewStory);
	$('#save_existing_button').bind('click', {st:this}, saveExistingStory);
	$('#publish_button').bind('click', {st:this}, publishStory);

	$('#story_category1, #story_category2').bind('change', {st:this}, function() {
		var otherId = /1$/.test(this.id) ? 'story_category2' : 'story_category1';
		var otherSelect = $('#' + otherId);
		var oldValue = otherSelect[0].value;
		otherSelect.find('option').remove();
		otherSelect.html($('#story_category_master').html());
		otherSelect.val(oldValue);
		if (this.value == 20) {
			var notWattyCats = new Array(2,10,16,19);
			for (var i=0;i<notWattyCats.length;i++) {
				otherSelect.find('option[value=' + notWattyCats[i] + ']').remove();
			}
			if (otherSelect.find('option:selected').length==0) {
				otherSelect.find('option').first().attr('selected','selected');
			}
		}
		if (this.value != 0) {
			otherSelect.find('option[value=' + this.value + ']').remove();
		}
		if (st.data['dirty'] == false) { st.setState('unsaved'); }
		return false;
	});

	$('.toggle_parts').live('click', {st:this}, function() {
		$(this).parent().hide();
		$(this).parent().parent().parent().parent().find('tr.story_part_row.hidden').toggleClass('hidden');
		return false;
	});

	$('a.hover_change').each(function() {
		var t = $(this).find('img.hover_change');
		var src1 = t.attr('src');
		var newSrc = src1.substring(src1.lastIndexOf('/'), src1.lastIndexOf('.'));
		var path = src1.substring(0, src1.lastIndexOf('/'));
		$(this).hover(
				function() {
					$(this).parent().parent().prev().find('.story_title').css('color', '#FF9500');
					$(this).find('img.hover_change').attr('src', path+(newSrc+'_over.'+/[^.]+$/.exec(src1)));
				},
				function() {
					$(this).parent().parent().prev().find('.story_title').css('color', '#1862B9');
					$(this).find('img.hover_change').attr('src', path+(newSrc+'.'+/[^.]+$/.exec(src1)));
				}
				);
	});

	$('tr.story_part_row, tr.story').live('hover', function (ev) {
		if (ev.type == 'mouseenter') {
			$(this).find('.story_hover').removeClass('hover_hidden').fadeIn();
			$(this).find('.story_part_container').addClass('story_part_container_hover');
			$(this).find('.solo_story_container').addClass('solo_story_container_hover');
		}
		if (ev.type == 'mouseleave') {
			$(this).find('.story_hover').addClass('hover_hidden');
			$(this).find('.story_part_container').removeClass('story_part_container_hover');
			$(this).find('.solo_story_container').removeClass('solo_story_container_hover');
		}
	});

	$('tr.story_group_header_row').live('hover', function (ev) {
		if (ev.type == 'mouseenter') {
			$(this).find('.story_group_hover').removeClass('hover_hidden').fadeIn();
			$(this).find('.story_group_container').addClass('story_group_container_hover');
		}
		if (ev.type == 'mouseleave') {
			$(this).find('.story_group_hover').addClass('hover_hidden');
			$(this).find('.story_group_container').removeClass('story_group_container_hover');
		}
	});

	$('.my_story_meta img').tipsy({ gravity: 'sw', live: true });
	$('.story_group_hover img, .story_hover img').tipsy({ gravity: 'sw', live: true });
	$('.story_group_title, .story_group_toggle, .solo_story_title').tipsy({ gravity: 'sw', live: true });
	$('.qq-upload-button, .publish_state_meta').tipsy({ gravity: 'sw', fade: true, live: true });

	$('#story_title').focus(function() {
		if ($('#story_title').hasClass("story_title_default")) {
			$('#story_title').val("");
			$('#story_title').removeClass('story_title_default');
		}
	});

	$('.change_cover').live('click', function () {
		if (!isMobile()) {
			var groupAttrs = $(this).attr('id').split('_');
			var groupID = groupAttrs[1];
			var groupOwner = groupAttrs[3];
			expandStoryCover(groupID, groupOwner, true);
		}
		return false;
	});

	$('.remove_cover').live('click', function () {
		return document.forms['cover_form'].submit();
	});

	$("#story_title, #story_tags, #story_copyright, #story_rating, #story_language, #story_source, #story_youtube, #story_photos, input:radio[name='story_flag1'], #story_distributable").bind('change', {st:this}, function() {
		if (st.data['dirty'] == false) { st.setState('unsaved'); }
	});
}

Story.prototype.getText = function() {
	if (typeof(tinyMCE) !== 'undefined') { // will be undefined if tinyMCE fails to load
		var editor = tinyMCE.get('story_text');
		return editor.getContent();
	}
	else {
		return $('#story_text').val();
	}
}

function storyEditorOnchange(ed) {
    if (ed.isDirty()) {
        st.setState('unsaved');
    }
    else {
        var state = ($('#story_id').val() === 'new') ? 'unsaved' : 'saved';
        st.setState(state);
    }
}

function autoSaveStory() {
	if (st.data['dirty'] == true) {
		clearInterval(st.data['autoSaveID']);
		st.data['autoSaveID'] = null;
		var storyData = st.getStoryData();
		storyData['text'] = st.getText();
		storyData['req_type'] = 'edit';
		st.save(storyData);
	}
}

var saveExistingStory = function() {
	if (!clickable || publishing)
		return false;
	clickable = false;
	var storyData = st.getStoryData();
	storyData['text'] = st.getText();
	storyData['req_type'] = 'edit';
	st.save(storyData, this);
	return false;
}

var saveNewStory = function() {
	if (!clickable || publishing)
		return false;
	clickable = false;
	var storyData = st.getStoryData();
	storyData['text'] = st.getText();
	storyData['terms'] = !($("input:checkbox[name='story_terms']:checked")[0] == undefined);
	storyData['req_type'] = 'new';
	st.save(storyData, this);
	return false;
}

var publishStory = function() {
	if (!clickable || publishing)
		return false;
	$("#publish_button").attr("disabled","disabled");
	publishing = true;
	clickable = false;
	var storyData = st.getStoryData();
	storyData['text'] = st.getText();
	storyData['publish'] = true;

	if (storyData['id'] === 'new') {
		storyData['req_type'] = 'new';
		storyData['terms'] = !($("input:checkbox[name='story_terms']:checked")[0] == undefined);
	}
	else {
		storyData['req_type'] = 'edit';
	}

	st.save(storyData, this);
	return false;
}
